<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <a-select v-model="model.brand" placeholder="请选择品牌">
                <a-select-option v-for="(item,index) in brandList" :key="item.id">{{ item.formulaName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="Fc No" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fcNo">
              <a-select v-model="model.fcNo" placeholder="请选择FC No">
                <a-select-option v-for="(item,index) in brandList" :key="item.id">{{ item.fcNo }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class='add-box'>
          <a-button type="link" icon="plus" @click='addCavity'>添加后配小料</a-button>
        </div>
        <a-form-model-item :labelCol="labelCol3" :wrapperCol="wrapperCol3">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                <div class='mark-infos' style="table-layout: fixed;">
                  <a-table
                    ref="markTable"
                    size="middle"
                    :scroll="{x:false,y:false}"
                    bordered
                    :rowKey="(record = () => record.id)"
                    :columns="columns"
                    :dataSource="model.eneFormulaPgOtherDetails"
                    :pagination="false"
                    :loading="loading"
                    class="j-table-force-nowrap1">
                    <template slot="action" slot-scope="text, record,index">
                      <a-popconfirm title="确定删除吗?" @confirm="() => deleteCavity(index)">
                        <a>删除</a>
                      </a-popconfirm>
                    </template>
                    <template v-for="col in ['ingredientId','ingredientName','fcRatio','color','allIngredients','halfIngredients']" :slot="col" slot-scope="text, record,index">
                      <div :key="record.id">
                        <a-form-model-item  v-if="col==='ingredientName'">
                          <j-search-select-tag v-model="record.ingredientName"
                                               dict="ene_ingredient_management,material_description,material_description"
                                               placeholder="请输入原料名称"
                                               @change="onChangeCode"
                                               :getPopupContainer="getPopupContainer"

                          />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='ingredientId'">
                          <a-input v-model="record.ingredientId" placeholder="请输入原料编号" disabled />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='fcRatio'">
                          <a-input
                            v-model="record.fcRatio"
                            placeholder="请输入配方卡比例"
                            @input="onChange(record)"
                          />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='color'">
                          <el-color-picker v-model="record.color" ></el-color-picker>
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='allIngredients'">
                          <a-input v-model="record.allIngredients"
                                   placeholder="请输入整批配料"
                                   :key="index"
                                   @input="index === 0 ? onChange(record) : null"
                                   :disabled="index!==0"
                          />
                        </a-form-model-item>
                        <a-form-model-item v-else-if="col==='halfIngredients'">
                          <a-input v-model="record.halfIngredients" placeholder="请输入半批配料"  disabled/>
                        </a-form-model-item>
                      </div>
                    </template>
                    <a-form-model-item>
                      <a-input></a-input>
                    </a-form-model-item>
                  </a-table>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-table
          ref="testTable"
          size="middle"
          :scroll="{x:false,y:false}"
          bordered
          :rowKey="id"
          :columns="fcRatioColumns"
          :dataSource="fcRatioList"
          :pagination="false"
          :loading="loading"
          :showHeader="false"
          class="j-table-force-nowrap1">
        </a-table>
        <a-table
          ref="testTable"
          size="middle"
          :scroll="{x:false,y:false}"
          bordered
          :rowKey="id"
          :columns="totalColumns"
          :dataSource="testList"
          :pagination="false"
          :loading="loading"
          :showHeader="false"
          class="j-table-force-nowrap1">
        </a-table>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
import 'element-ui/lib/theme-chalk/index.css';
import Decimal from 'decimal.js';

  export default {
    name: 'EneFormulaPgOtherForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          eneFormulaPgOtherDetails:[
            {
              id: '',
              ingredientId: '',
              ingredientName: '',
              fcRatio: '',
              color: '',
              allIngredients: '',
              halfIngredients: ''
            }
          ]
         },
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function(t, r, index) {
              return parseInt(index) + 1
            }
          },
          {
            title: '原料编码',
            align: 'center',
            dataIndex: 'ingredientId',
            width: 160,
            scopedSlots: { customRender: 'ingredientId' }
          },
          {
            title: '原料名称',
            align: 'center',
            dataIndex: 'ingredientName',
            width: 160,
            scopedSlots: { customRender: 'ingredientName' }
          },
          {
            title: '配方卡比例',
            align: 'center',
            dataIndex: 'fcRatio',
            scopedSlots: { customRender: 'fcRatio' }
          },
          {
            title: '色标',
            align: 'center',
            dataIndex: 'color',
            width: 160,
            scopedSlots: { customRender: 'color' }
          },
          {
            title: '整批配料',
            align: 'center',
            dataIndex: 'allIngredients',
            scopedSlots: { customRender: 'allIngredients' }
          },
          {
            title: '半批配料',
            align: 'center',
            dataIndex: 'halfIngredients',
            scopedSlots: { customRender: 'halfIngredients' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        totalColumns: [
          {
            title: '标题',
            align: "center",
            width:695,
            dataIndex: 'title',
          },
          {
            title: '整批小料总重量',
            align: "center",
            width:144,
            dataIndex: 'totalAllIngredients',
          },
          {
            title:'半批小料总重量',
            align:"center",
            width:144,
            dataIndex: 'totalHalfIngredients',
          },
          {
            title:'操作',
            align:"center",
            dataIndex: 'action',
          },
        ],
        fcRatioColumns :
        [
        {
            title: '序号',
            align: "center",
            width:230,
            dataIndex: 'title',
        },
        {
           title:'配方总比例',
           align:"center",
           width:144,
           dataIndex: 'totalFcRatio',
        },
        ],
        fcRatioList:[
          {
            title: '配方总比例',
            totalFcRatio: '',
            action: '',
          }
        ],
        testList: [],
        loading: false,
        brandList:[],// 品牌
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol3: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
        },
        url: {
          brandList:'/craft/eneFormulaPgBase/list',
          add: "/craft/eneFormulaPgOther/add",
          edit: "/craft/eneFormulaPgOther/edit",
          queryById: "/craft/eneFormulaPgOther/queryById"
        }
      }
    },

    mounted() {
      this.getBrandList();
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      getBrandList(){
        getAction(this.url.brandList,{ pageSize: 100 }).then((res) => {
          if(res.success){
            this.brandList = res.result.records;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      getPopupContainer(triggerNode) {
        return document.body; // 将下拉框渲染到 body 上
      },
      addCavity() {
        console.log("addCavity",this.model.eneFormulaPgOtherDetails)
        if (!this.model.eneFormulaPgOtherDetails) {
          this.$set(this.model, 'eneFormulaPgOtherDetails', [])
        }
        this.model.eneFormulaPgOtherDetails.push({
          id: '',
          ingredientId: '',
          ingredientName: '',
          fcRatio: '',
          color: '',
          allIngredients: '',
          halfIngredients: ''
        })
      },
      deleteCavity(originalIndex) {
        let len = this.model.eneFormulaPgOtherDetails.length
        if (len > 1) {
          this.model.eneFormulaPgOtherDetails.splice(originalIndex, 1)
        } else {
          this.$message.error('最少保留一个后配小料！')
        }
      },
      onChange(record){
        if(record){
          postAction('/craft/eneFormulaPgOther/compute/other',{
            brand : this.model.brand,
            firstFcRatio : this.model.eneFormulaPgOtherDetails[0].fcRatio,
            firstAllIngredients : this.model.eneFormulaPgOtherDetails[0].allIngredients,
            eneFormulaPgOtherDetails : this.model.eneFormulaPgOtherDetails
            }).then(
            (res)=>{
              if(res.success){
                console.log("到这了啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊")
                let totalAll = new Decimal(0);
                let totalHalf = new Decimal(0);
                let totalCreatAll = new Decimal(0);
                let totalCreatHalf = new Decimal(0);
                let totalFcRatio = new Decimal(0);
                this.testList=[];
                this.testList.push(
                  {
                    title: '每批小料总重量：',
                    totalAllIngredients: '12',
                    totalHalfIngredients: '6',
                    action: '',
                  },
                  {
                  title: '每整（半）批小料可生产成品数量（吨）：',
                  totalAllIngredients: '12',
                  totalHalfIngredients: '6',
                  action: '',
                })
                for(let i = 0; i < res.result.length; i++){
                  this.$set(this.model.eneFormulaPgOtherDetails[i], 'allIngredients', res.result[i].allIngredients);
                  this.$set(this.model.eneFormulaPgOtherDetails[i], 'halfIngredients', res.result[i].halfIngredients);
                  totalAll=totalAll.plus(new Decimal(res.result[i].allIngredients));
                  totalFcRatio=totalFcRatio.plus(new Decimal(res.result[i].fcRatio));
                }
                totalHalf=totalAll.dividedBy(2);
                totalCreatAll=totalAll.dividedBy(totalFcRatio).dividedBy(1000);
                totalCreatHalf=totalCreatAll.dividedBy(2);
                this.$set(this.testList[0], 'totalAllIngredients', totalAll.toNumber());
                this.$set(this.testList[0], 'totalHalfIngredients', totalHalf.toNumber());
                this.$set(this.testList[1], 'totalAllIngredients', totalCreatAll.toNumber());
                this.$set(this.testList[1], 'totalHalfIngredients', totalCreatHalf.toNumber());
                this.fcRatioList[0].totalFcRatio = totalFcRatio.toNumber();
              }
            })
        }
      },
      onChangeCode(record){
        if(record){
          postAction('/craft/eneFormulaPgOther/compute/otherCode',{brand : this.model.brand, firstFcRatio : this.model.eneFormulaPgOtherDetails[0].fcRatio, eneFormulaPgOtherDetails : this.model.eneFormulaPgOtherDetails}).then(
            (res)=>{
              if(res.success){
                console.log("到这了啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
                for(let i = 0; i < res.result.length; i++){
                  this.$set(this.model.eneFormulaPgOtherDetails[i], 'ingredientId', res.result[i].ingredientId);
                }

              }
            })
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
          this.model = Object.assign({}, record);
        //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        if(this.disabled){
          this.isEdit = false;
        }else{
          this.isEdit = true;
        }
        this.visible = true;

        let totalAll = new Decimal(0);
        let totalHalf = new Decimal(0);
        let totalCreatAll = new Decimal(0);
        let totalCreatHalf = new Decimal(0);
        let totalFcRatio = new Decimal(0);
        this.testList=[];
        this.testList.push(
          {
            title: '每批小料总重量：',
            totalAllIngredients: '0',
            totalHalfIngredients: '0',
            action: '',
          },
          {
            title: '每整（半）批小料可生产成品数量（吨）：',
            totalAllIngredients: '0',
            totalHalfIngredients: '0',
            action: '',
          })
        for(let i = 0; i < this.model.eneFormulaPgOtherDetails.length; i++){
          totalAll=totalAll.plus(new Decimal(this.model.eneFormulaPgOtherDetails[i].allIngredients));
          totalFcRatio=totalFcRatio.plus(new Decimal(this.model.eneFormulaPgOtherDetails[i].fcRatio));
        }
        totalHalf=totalAll.dividedBy(2);
        totalCreatAll=totalAll.dividedBy(totalFcRatio).dividedBy(1000);
        totalCreatHalf=totalCreatAll.dividedBy(2);
        this.$set(this.testList[0], 'totalAllIngredients', totalAll.toNumber());
        this.$set(this.testList[0], 'totalHalfIngredients', totalHalf.toNumber());
        this.$set(this.testList[1], 'totalAllIngredients', totalCreatAll.toNumber());
        this.$set(this.testList[1], 'totalHalfIngredients', totalCreatHalf.toNumber());
        this.fcRatioList[0].totalFcRatio = totalFcRatio.toNumber();

      },
      submitForm () {
        const that = this;
        for(let i = 0; i < this.model.eneFormulaPgOtherDetails.length; i++){
          if(this.model.eneFormulaPgOtherDetails[i].ingredientName === ""){
            this.$message.warning("请选择原料名称");
            return;
          }
          if(this.model.eneFormulaPgOtherDetails[i].ingredientId === ""){
            this.$message.warning("请等待原料代码查询");
            return
          }

        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
    }
  }
</script>
<style lang="scss" scoped>
.title {
  font-size: 24px;
  font-weight: bold;
}

.unit {
  padding-left: 4px;
  line-height: 40px;
}

.query-group-cust {
  width: 100% !important;
}

.ant-input-number {
  width: 100% !important;
}

.cavity-box {
  .title-box {
    height: 40px;
    padding: 0 5px;
    line-height: 40px;

    span {
      font-size: 24px;
      font-weight: bold;
      float: left;
    }

    .ant-btn-link {
      float: right;
    }
  }

  .mark-infos {
    position: relative;

    .editable-add-btn {
      position: absolute;
      top: 10px;
      right: 18px;
      z-index: 202;
    }
  }
}
::v-deep .ant-table-row {
  height:63px !important;
}
</style>